package com.ck.controller.student;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Student;
import com.ck.service.StudentService;

public class EditStudentOwnInfoController extends SimpleFormController {
	
	private StudentService studentService;

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}
	
	protected Object formBackingObject(HttpServletRequest request)
		throws Exception {
		Integer studentID = (Integer) request.getSession().getAttribute("studentID");
		Student student = studentService.gainStudent(studentID);
		
		return student;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {
		
		Student student = (Student) command;
		Map model = errors.getModel();
		
		//后台校验
        boolean flag = true;
        String email = student.getEmail().trim();
        
        if( email == null || "".equals(email) ){
        	student.setEmail(null);
        }else{
	        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
			Matcher m = p.matcher(email);
			if(!m.matches()){
				model.put("error_email", "email格式不正确");
				flag = false;
			}
        }
		
		if(email.length() > 40){
			model.put("error_email", "email长度：0-40个字符");
			flag = false;
		}
        
		//校验不通过
		if(!flag){
			return new ModelAndView(getFormView(), model);
		}
		
		Integer studentID = (Integer) request.getSession().getAttribute("studentID");
		student.setId(studentID);
		
		boolean isEditStudentOwnInfoSuccess = studentService.editStudentOwnInfo(student);
		
		if (isEditStudentOwnInfoSuccess) {
			return new ModelAndView("redirect:showStudentOwnInfo.html");
            //return new ModelAndView(getSuccessView());
        } else {
            return new ModelAndView(getFormView(), model);
        }
	}
}
